<template>
    <up-popup :show="show" @close="emit('close')" :close-on-click-overlay="true">
        <view flex flex-col p-2>
            <view text-center font-bold p-4 text-gray-500>{{task.task}}</view>
            <up-cell-group>
                <up-cell v-if="task.status==0" @click="handleTask(1)" text-center text-40 p-2 title="开始任务"></up-cell>
                <up-cell v-if="task.status!=2" @click="handleTask(2)" text-center text-40 p-2 title="完成任务"></up-cell>
                <up-cell  @click="emit('close')" text-center text-gray-500 p-2 title="取消"></up-cell>
            </up-cell-group>
        </view>
        
    </up-popup>
</template>
<script lang="ts" setup>
    import { defineProps } from 'vue';
    import {Task} from '@/types/task'
    import {apiStartTask,apiCompleteTask} from '@/api/task'
    import {TaskOpEvent} from '@/enums/taskEnums';
    const props = defineProps({
        show:{
            type:Boolean,
            default:false
        },
        task:{
            type:Object as () => Task,
            default:null
        }
    })

    const handleDo = (item: Task) => {
        uni.showModal({
            title: '完成任务',
            content: '确定完成任务吗?',
            success: function (res) {
                if (res.confirm) {
                    apiCompleteTask({ task_id: item.id,task_list_id: item.list_id}).then(() => {
                        item.status = 2
                        uni.$u.toast('完成成功')
                        emit('update', item)
                    }).catch((msg) => {
                        console.log(msg)
                        uni.$u.toast('完成失败:'+msg)
                    })
                }
            }
        });
    }

    const emit = defineEmits<{
        (event: 'update', show: Task): void
        (event: 'close'): void
    }>()

    const handleTask = (status:number) => {
        if(status==1){
            apiStartTask({ task_id: props.task.id,task_list_id: props.task.list_id}).then(() => {
                uni.$u.toast('开始成功')
                props.task.status = 1
                emit('update',props.task)
            }).catch((msg) => {
                console.log(msg)
                uni.$u.toast('开始失败:'+msg)
            })
            return
        }else if(status==2){
            handleDo(props.task)
            return
        }
        emit('update',props.task)
    }
</script>
<style>
</style>